package org.dromara.mall.service.impl;

import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.mall.domain.TerMallProduct;
import org.dromara.mall.domain.vo.TerMallProductVo;
import org.dromara.mall.mapper.TerMallProductMapper;
import org.dromara.mall.service.ITerFullSyncService;
import org.dromara.mall.service.ITerMallProductService;
import org.springframework.stereotype.Service;
import org.dromara.mall.domain.bo.TerMallCartBo;
import org.dromara.mall.domain.vo.TerMallCartVo;
import org.dromara.mall.domain.TerMallCart;
import org.dromara.mall.mapper.TerMallCartMapper;
import org.dromara.mall.service.ITerMallCartService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 购物车Service业务层处理
 *
 * @author xch
 * @date 2025-06-27
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TerMallCartServiceImpl implements ITerMallCartService {

    private final TerMallCartMapper baseMapper;
    private final ITerMallProductService terMallProductService;
    private final ITerFullSyncService terFullSyncService;
    /**
     * 查询购物车
     *
     * @param id 主键
     * @return 购物车
     */
    @Override
    public TerMallCartVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询购物车列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 购物车分页列表
     */
    @Override
    public TableDataInfo<TerMallCartVo> queryPageList(TerMallCartBo bo, PageQuery pageQuery) {
        bo.setUserId(LoginHelper.getAppLoginUser()!=null?LoginHelper.getAppLoginUser().getId():bo.getUserId());
        LambdaQueryWrapper<TerMallCart> lqw = buildQueryWrapper(bo);
        Page<TerMallCartVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
    @Override
    public List<TerMallCartVo> queryList(TerMallCartBo bo) {
        LambdaQueryWrapper<TerMallCart> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询符合条件的购物车列表
     *
     * @param bo 查询条件
     * @return 购物车列表
     */
    @Override
    public List<TerMallProductVo> queryProductList(TerMallCartBo bo) {
        LambdaQueryWrapper<TerMallCart> lqw = buildQueryWrapper(bo);
        List<TerMallCartVo> list = baseMapper.selectVoList(lqw);
        List<TerMallProductVo> voList = new ArrayList<>();
        list.forEach(vo -> {
            TerMallProductVo product= terMallProductService.queryById(vo.getProductId());
            product.setQuantity(vo.getQuantity());
            product.setSelected(vo.getSelected());
            product.setCartId(vo.getId());
            voList.add(product);
        });
        return voList;
    }

    private LambdaQueryWrapper<TerMallCart> buildQueryWrapper(TerMallCartBo bo) {
        LambdaQueryWrapper<TerMallCart> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TerMallCart::getId);
        lqw.eq(bo.getUserId() != null, TerMallCart::getUserId, bo.getUserId());
        lqw.eq(bo.getProductId() != null, TerMallCart::getProductId, bo.getProductId());
        lqw.eq(bo.getQuantity() != null, TerMallCart::getQuantity, bo.getQuantity());
        lqw.eq(bo.getSelected() != null, TerMallCart::getSelected, bo.getSelected());
        return lqw;
    }

    /**
     * 新增购物车
     *
     * @param bo 购物车
     * @return 是否新增成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(TerMallCartBo bo) {
        if(terFullSyncService.judgeInventory(bo.getProductId(),bo.getQuantity())){
            TerMallCart add = MapstructUtils.convert(bo, TerMallCart.class);
            validEntityBeforeSave(add);
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
            }
            return flag;
        }else{
            TerMallProductVo product = terMallProductService.queryById(bo.getProductId());
            throw new ServiceException("商品"+product.getName()+"库存不足！");
        }
    }

    /**
     * 修改购物车
     *
     * @param bolist 购物车
     * @return 是否修改成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(List<TerMallCartBo> bolist) {
        int num =0;
        for (TerMallCartBo bo : bolist) {
            Long productId = bo.getId();
            bo.setProductId(productId);
            bo.setId(bo.getCartId());
            if(terFullSyncService.judgeInventory(bo.getProductId(),bo.getQuantity())){
                TerMallCart update = MapstructUtils.convert(bo, TerMallCart.class);
                validEntityBeforeSave(update);
                num= baseMapper.updateById(update) ;
            }else{
                TerMallProductVo product = terMallProductService.queryById(bo.getProductId());
                throw new ServiceException("商品"+product.getName()+"库存不足！");
            }
        }
        return num>0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TerMallCart entity){
        //TODO 做一些数据校验,如唯一约束
    }
    @Override
    public Boolean deleteWithValidById(String id) {
        return baseMapper.deleteById(id) > 0;
    }
    /**
     * 校验并批量删除购物车信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


}
